package com.lqk.netty.server;

import com.lqk.netty.handler.HeartBeatHandler;
import com.lqk.netty.handler.ServerChannelInitializer;
import com.lqk.netty.handler.ServerHandler;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

import com.lqk.netty.common.protobuf.MessageModule;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.protobuf.ProtobufDecoder;
import io.netty.handler.codec.protobuf.ProtobufEncoder;
import io.netty.handler.codec.protobuf.ProtobufVarint32FrameDecoder;
import io.netty.handler.codec.protobuf.ProtobufVarint32LengthFieldPrepender;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.timeout.IdleStateHandler;
import lombok.extern.slf4j.Slf4j;

/**
 * @author liqiankun@nnuo.com
 * @date 2023/3/30 17:02
 * @description Netty Server
 **/
@Slf4j
public class Server {

    public static final int PORT = 7099;

    public Server() {
        /*
          配置服务端的NIO线程组
          bossGroup 只是处理连接请求，workerGroup 是真正与客户端进行业务交互处理
          两个都是无限循环
          bossGroup 和 workerGroup含有的子线程（NioEventLoop）的个数默认：实际CPU核数*2
          也可以自己指定线程数
         */
        EventLoopGroup bossGroup = new NioEventLoopGroup(4);
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        ServerBootstrap b = new ServerBootstrap();
        try {
            b.group(bossGroup, workerGroup)
                    // 使用NioServerSocketChannel 作为服务器的通道实现
                    .channel(NioServerSocketChannel.class)
                    // 设置线程队列等待连接的个数
                    .option(ChannelOption.SO_BACKLOG, 128)
                    // 设置保持活动连接状态 快速复用端口
                    .option(ChannelOption.SO_REUSEADDR, true)
                    //缓存区 池化操作
                    .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
                    // 该 handler 对应 bossGroup（在 bossGroup 生效），childHandler 对应 workerGroup（在 workerGroup 中生效）
                    .handler(new LoggingHandler(LogLevel.INFO))
                    .childHandler(new ServerChannelInitializer());
            // 	绑定端口，同步等待成功
            ChannelFuture cf = b.bind(PORT).sync();
            log.info(" Netty Server startup.. port: {}", PORT);
            // 给cf注册一个监听器，监控我们关心的事件
            cf.addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                    if (cf.isSuccess()){
                        System.out.println("监听端口 6668 成功");
                    }else {
                        System.out.println("监听端口 6668 失败");
                    }
                }
            });
            cf.channel().closeFuture().sync();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
            log.info(" Netty Server shutdown.. ");
        }
    }
}
